
ActiveScaffold rescue
  raise "ActiveScaffoldSchema depends on ActiveScaffold. Enable the plugin first"
ActiveScaffold::Helpers::ListColumns rescue
  raise "ActiveScaffoldSchema works only ActiveScaffold-1.1.0rc1 or higher"


ActiveScaffold::Config::Search.class_eval do
  def colors
    unless @colors
      @colors
      self.colors = %w( #FFFF66 #A0FFFF #99FF99 #FF9999 #FF66FF )
    end
    @colors
  end

  def colors=(val)
    raise "'colors' should be an Array" unless val.is_a?(Array)
    raise "'colors' should not be empty" if val.blank?
    @colors = val
  end
end

module ActiveScaffold::Helpers::ListColumns
  module HighlightPatch
    def render_list_column(text, column, record)
      search = active_scaffold_config.search rescue nil # TODO: this kills performance
      if column.link or !search or !search.columns.any?{|col| col.name == column.name}
        super
      else
        render_list_column_highlight(text, column, record)
      end
    end

    def render_list_column_highlight(text, column, record)
      keywords = @query.to_s.split(/\s+/).sort_by(&:size).reverse
      return text if keywords.blank?

      text = text.to_s.dup
      hits = []

      # mark
      keywords.each_with_index do |keyword, i|
        regexp = /#{Regexp.escape(keyword)}/i
        text.gsub!(regexp) {hits << $&; [i].pack("c")}
      end

      # replace
      colors = active_scaffold_config.search.colors
      hits.each_with_index do |hit, i|
        color = colors[i%colors.size]
        html  = %Q{<b style="color: black; background-color: #{color};">#{hit}</b>}
        text.gsub!([i].pack("c"), html)
      end

      return text
    end
  end
end

ActionView::Base.send(:include, ActiveScaffold::Helpers::ListColumns::HighlightPatch)

